package com.freewater.library.lending.book.infrastructure.po;

import com.freewater.library.lending.book.infrastructure.model.BookInstanceImpl;
import com.freewater.library.lending.book.model.BookInstance;
import jakarta.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

@Table(name = "book_instance",
        uniqueConstraints = {
                @UniqueConstraint(columnNames = {"qr_code"})
        })
@Entity
@Data
@NoArgsConstructor
public class BookInstancePo {
    /**
     * 主键ID
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    /**
     * 二维码
     */
    private String qrCode;
    /**
     * ISBN
     */
    private String isbn;
    /**
     * 是否已下架
     */
    private boolean takenOff;
    /**
     * 是否已预定
     */
    private boolean reserved;
    /**
     * 是否已借出
     */
    private boolean checkedOut;
    /**
     * 是否已遗失
     */
    private boolean lost;
    /**
     * 读者ID
     */
    private Long reservedBy;
    /**
     * 预定时间
     */
    private LocalDateTime reservedAt;
    /**
     * 借出人ID
     */
    private Long checkedOutBy;
    /**
     * 借出时间
     */
    private LocalDateTime checkedOutAt;
    /**
     * 借出是否已超时
     */
    private Boolean checkedOutOverdueMarked;
    /**
     * 乐观锁版本
     */
    @Version
    private int version;

    public BookInstancePo(BookInstance bookInstance) {
        this.qrCode = bookInstance.getQrCode();
        this.isbn = bookInstance.getIsbn();
        this.takenOff = bookInstance.isTakenOff();
        this.reserved = bookInstance.isReserved();
        this.checkedOut = bookInstance.isCheckedOut();
        this.lost = bookInstance.isLost();
        this.reservedBy = bookInstance.getReservedBy();
        this.reservedAt = bookInstance.getReservedAt();
        this.checkedOutBy = bookInstance.getCheckedOutBy();
        this.checkedOutAt = bookInstance.getCheckedOutAt();
        this.checkedOutOverdueMarked = bookInstance.getCheckedOutOverdueMarked();
        if (bookInstance instanceof BookInstanceImpl bookInstanceImpl) {
            this.id = bookInstanceImpl.getDbId();
            this.version = bookInstanceImpl.getVersion();
        } else {
            this.version = 0;
        }
    }
    public static BookInstance convert(BookInstancePo record) {
        BookInstanceImpl bookInstance = new BookInstanceImpl(record.getQrCode(),
                record.getIsbn(),
                record.isTakenOff(),
                record.isReserved(),
                record.isCheckedOut(),
                record.isLost(),
                record.getReservedBy(),
                record.getReservedAt(),
                record.getCheckedOutBy(),
                record.getCheckedOutAt(),
                record.getCheckedOutOverdueMarked()
        );
        bookInstance.setDbId(record.getId());
        bookInstance.setVersion(record.getVersion());
        return bookInstance;
    }
}